<template>
  <div>
    <!-- 搜索页面头部 -->
    <div class="search-header">
      <!-- 后退按钮 -->
      <van-icon name="arrow-left" color="white" size="0.48rem" class="goback" @click="$router.back()" />
      <!-- 搜索组件 -->
      <van-search placeholder="请输入搜索关键词" background="#007BFF" v-model.trim="kw" shape="round" ref="search"
        @input="inputFn" @search="searchFn"/>
    </div>

    <!-- 搜索建议列表 -->
    <div class="sugg-list" v-if="suggestList.length !== 0">
      <div class="sugg-item" v-for="(item,index) in suggestList" :key="index" v-html="lightFn(item,kw)" @click="suggestClickFn(item)">
      </div>
    </div>

    <!-- 搜索历史 -->
    <div class="search-history" v-else>
      <!-- 标题 -->
      <van-cell title="搜索历史">
        <!-- 使用 right-icon 插槽来自定义右侧图标 -->
        <template #right-icon>
          <van-icon name="delete" class="search-icon" @click="clearHistoryFn"/>
        </template>
      </van-cell>

      <!-- 历史列表 -->
      <div class="history-list">
        <span class="history-item" v-for="(str,index) in history" :key="index" @click="historyClickFn(str)">{{str}}</span>
      </div>
    </div>
  </div>
</template>

<script>
import {
  suggestListAPI
} from '@/api'
export default {
  name: 'Search',
  data () {
    return {
      kw: '', // 搜索关键字
      timer: null, // 放抖定时器
      suggestList: [], // 联想建议数据,下方的列表
      history: JSON.parse(localStorage.getItem('his')) || [] // 搜索历史
    }
  },
  mounted () {
    // 自动聚焦
    const inp = this.$refs.search.querySelector('input')
    inp.focus()
  },
  methods: {
    // 输入框实时输入触发的事件
    inputFn () {
      if (!this.kw.trim()) {
        this.suggestList = []
        return
      }
      clearTimeout(this.timer)
      this.timer = setTimeout(() => {
        this.getsuggestList()
      }, 500)
    },
    async getsuggestList () {
      const result = await suggestListAPI(this.kw)
      if (result.data.data.options[0]) {
        this.suggestList = result.data.data.options
      }
    },
    // 处理字符串高亮
    lightFn (originStr, target) {
      if (originStr) {
        const reg = new RegExp(target, 'ig')
        return originStr.replace(reg, (match) => {
          return `<span style="color:red;">${match}</span>`
        })
      }
    },
    // 确认搜索时触发
    searchFn () {
      if (this.kw.length > 0) {
        this.history.unshift(this.kw)
        setTimeout(() => {
          this.$router.push({
            path: `/search_result/${this.kw}`
          })
        }, 0)
      }
    },
    // 联想列表点击触发
    suggestClickFn (str) {
      this.history.unshift(str)
      setTimeout(() => {
        this.$router.push({
          path: `/search_result/${str}`
        })
      }, 0)
    },
    // 搜索记录点击触发
    historyClickFn (str) {
      this.history.unshift(str)
      this.$router.push({
        path: `/search_result/${str}`
      })
    },
    // 垃圾桶清理搜索历史
    clearHistoryFn () {
      this.history = []
    }
  },
  watch: {
    // 监听history  保存到本地
    history: {
      deep: true,
      handler () {
        // 数组去重
        const arr = [...new Set(this.history)]
        localStorage.setItem('his', JSON.stringify(arr))
      }
    }
  }
}

</script>

<style scoped lang="less">
  .search-header {
    height: 46px;
    display: flex;
    align-items: center;
    background-color: #007bff;
    overflow: hidden;

    /*后退按钮*/
    .goback {
      padding-left: 14px;
    }

    /*搜索组件*/
    .van-search {
      flex: 1;
    }
  }

  /*搜索建议列表样式 */
  .sugg-list {
    .sugg-item {
      padding: 0 15px;
      border-bottom: 1px solid #f8f8f8;
      font-size: 14px;
      line-height: 50px;
      // 实现省略号的三行代码
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
  }

  /**搜索历史 */
  .search-icon {
    font-size: 16px;
    line-height: inherit;
  }

  .history-list {
    padding: 0 10px;

    .history-item {
      display: inline-block;
      font-size: 12px;
      padding: 8px 14px;
      background-color: #efefef;
      margin: 10px 8px 0px 8px;
      border-radius: 10px;
    }
  }

</style>
